package com.foreveross.mofang.datapersistence.infra.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.inject.Inject;
import javax.inject.Named;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.foreveross.mofang.datapersistence.infra.Constant;
import com.foreveross.mofang.datapersistence.infra.service.IDataPersistenceMsgService;
import com.foreveross.mofang.datapersistence.infra.utils.CacheUtils;
import com.foreveross.mofang.datapersistence.infra.utils.MoFangLogger;
import com.foreveross.mofang.datapersistence.infra.utils.PropertiesUtil;
import com.foreveross.taskservice.common.application.crawlnode.ICrawlNodeBaseTaskApplication;
import com.foreveross.taskservice.common.bean.AbstractTask;


/**
 * 数据持久化后消息发送服务仓储实现
 * 
 * @author fb
 */
@SuppressWarnings("deprecation")
@Named
public class DataPersistenceMsgServiceImpl implements IDataPersistenceMsgService{

	private final static Logger logger = MoFangLogger.MQ_MESSAGE.getLogger();
	
	private final Map<String, Destination> destCache = new HashMap<String, Destination>();
	
	@Inject
	private JmsTemplate jmsTopicTemplate;
	@Inject
	private ICrawlNodeBaseTaskApplication iCrawlNodeBaseTaskApplication;
	
	public void sendMessage(Destination destination, final String message) {  
		
        jmsTopicTemplate.send(destination, new MessageCreator() {  
            public Message createMessage(Session session) throws JMSException {  
                return session.createTextMessage(message);  
            }  
        });  
        
        logger.info("发送消息 destination:{}, 内容为：{}", destination, message);
    }   
	
	public void sendTopicMessage(String destination, final String message) {  
		Destination destinationObj = destCache.get(destination);
		
		if (destinationObj == null) {
			destinationObj = new ActiveMQTopic(destination);
			destCache.put(destination, destinationObj);
		}
		
        jmsTopicTemplate.send(destination, new MessageCreator() {  
            public Message createMessage(Session session) throws JMSException {  
                return session.createTextMessage(message);  
            }  
        });  
        
        logger.info("发送消息 destination:{}, 内容为：{}", destination, message);
    }   
	
	public void sendMessage(final String message) {  
		
        jmsTopicTemplate.send(new MessageCreator() {  
            public Message createMessage(Session session) throws JMSException {  
                return session.createTextMessage(message);  
            }  
        });  
        
        logger.info("toplic默认发送消息内容为：{}", message);
    }   
	
	public void roolbackTaskQueueRecordEntity(AbstractTask task) {
		logger.info("taskId:{},count:{},error：{}", new Object[] { task.getId(),
				task.getCrawlCount(), task.getExcuteCount() });
		
		Properties sysPro = PropertiesUtil.getProperties(Constant.PROPERTIES_SYSTEM, CacheUtils.CacheInstance.SYSTEM);

		
		try {
			if (Boolean.valueOf(sysPro.getProperty("system.mq.taskPersistence.mqIsRoolback", "false"))) {
				iCrawlNodeBaseTaskApplication.roolbackTaskQueueRecordEntity(task);
			}
		} catch (Exception e) {
			logger.error("消息发送异常：{}", e.getMessage());
		}
	}
}
